package com.zdft.promotion.asyn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zdft.promotion.asyn.bean.AsynPushBean;
import com.zdft.promotion.asyn.mapper.AsynPushBeanMapper;
import com.zdft.promotion.asyn.service.api.IAsynDealService;
import com.zdft.promotion.rabbitmq.domain.QueueEnum;
import com.zdft.promotion.rabbitmq.model.PushModel;
import com.zdft.promotion.rabbitmq.service.api.IMesssageService;
import com.ztft.zbus.tts.annotation.TriggeredServerClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@TriggeredServerClass
public class AsynPushDealServiceImpl extends ServiceImpl<AsynPushBeanMapper, AsynPushBean> implements IAsynDealService {

    @Value("${pushtoerp}")
    Integer pushtoerp;

    @Autowired
    IMesssageService messsageService;

    @Autowired
    AsynPushBeanMapper asynPushBeanMapper;

    @Override
    public void addMq(AsynPushBean bean, QueueEnum queueEnum) {
        if (pushtoerp == null || !pushtoerp.equals(1)) {
            System.out.println("当前已经停止同步");
            return;
        }
        bean.setCreateTime(new Date());
        if (asynPushBeanMapper.insert(bean) > 0) {
            try {//如果插入队列失败的话，不影响正常逻辑
                PushModel model = getPushModel(bean);
                messsageService.addOrderMessageToQueue(model, queueEnum);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public AsynPushBean getAsynPushByKey(String key) {
        QueryWrapper<AsynPushBean> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(AsynPushBean::getKey, key);
        return asynPushBeanMapper.selectOne(queryWrapper);
    }

    private PushModel getPushModel(AsynPushBean bean) {
        if (bean == null) {
            return null;
        }
        PushModel model = new PushModel();
        model.setType(bean.getType());
        model.setKey(bean.getKey());
        model.setSourceId(bean.getRefrenceId());
        model.setConsumerType(bean.getConsumerType());
        return model;
    }
}
